package com.itheima.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.itheima.common.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;

/**
 * @Author itheima
 * @Date 2022/5/6 14:50
 */
@Configuration
@Slf4j
public class MpConfig {
    //配置分页插件
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return mybatisPlusInterceptor;
    }

    /**
     * 自动填充：元数据对象处理器（填充具体内容）
     */
    @Bean
    public MetaObjectHandler metaObjectHandler() {
        MetaObjectHandler metaObjectHandler = new MetaObjectHandler() {
            /***
             * 当做insert操作的时候，填充具体值
             * @param metaObject
             */
            @Override
            public void insertFill(MetaObject metaObject) {
                log.info("线程名称{},线程id{}", Thread.currentThread().getName(), Thread.currentThread().getId());
                this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
                this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
                this.strictInsertFill(metaObject, "createUser", Long.class, BaseContext.getThreadLocalId());
                this.strictInsertFill(metaObject, "updateUser", Long.class, BaseContext.getThreadLocalId());
            }

            /**
             * 当做update操作的时候，填充具体值
             * @param metaObject
             */
            @Override
            public void updateFill(MetaObject metaObject) {
                this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
                this.strictUpdateFill(metaObject, "updateUser", Long.class, BaseContext.getThreadLocalId());
            }
        };
        return metaObjectHandler;
    }
}
